package com.hengxinguotong.zhihuichengjian.ui.statistics.attendance;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.CompanySelectAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Company;
import com.hengxinguotong.zhihuichengjian.bean.CompanyListRes;
import com.hengxinguotong.zhihuichengjian.treeview.RecyclerAdapter;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.PullableRecyclerView;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @CopyRight 恒信国通信息科技
 * @Author WuLei
 * @Date 2019/4/4
 * <p>
 * 选择公司
 */

public class CompanySelectActivity extends BaseActivity implements CompanySelectAdapter.OnClickListener, View.OnClickListener {
    @BindView(R.id.back_tv)
    HXTextView backTv;
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.refresh_list)
    PullToRefreshLayout refreshList;
    @BindView(R.id.empty_img)
    ImageView emptyImg;
    private PullableRecyclerView dataRv;

    private Intent intent;
    private List<Company> companyList;
    private CompanySelectAdapter companyAdapter;
    private int pageIndex = 1;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case Constants.UPDATE:
                    List<Company> datas = (List<Company>) msg.obj;
                    bindData(datas);
                    break;
            }
        }
    };

    private void bindData(List<Company> datas) {
        if (pageIndex == 1)
        {
            refreshList.refreshFinish(PullToRefreshLayout.SUCCEED);
            companyList = datas;
        } else
        {
            refreshList.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            companyList.addAll(datas);
        }
        showEmptyView(companyList.size() == 0);
        if (datas.size() >= Utils.ONCECOUNT)
        {
            refreshList.setPullUpEnable(true);
        } else
        {
            refreshList.setPullUpEnable(false);
        }
        companyAdapter.setDataList(companyList);
    }

    private void showEmptyView(boolean isEmpty){
        if(isEmpty){
            emptyImg.setVisibility(View.VISIBLE);
        }else {
            emptyImg.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_company_select);
        ButterKnife.bind(this);
        intent = getIntent();
        companyList = (List<Company>) intent.getSerializableExtra("companyList");
        if(companyList == null){
            initData();
        }
        initView();
    }

    private void initView() {
        refreshList.setPullUpEnable(false);
        refreshList.setOnPullListener(pullListener);
        dataRv = (PullableRecyclerView) refreshList.getPullableView();
        companyAdapter = new CompanySelectAdapter(this, companyList);
        companyAdapter.setOnClickListener(this);
        dataRv.setAdapter(companyAdapter);
        dataRv.setItemAnimator(new DefaultItemAnimator());
        dataRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        showEmptyView(companyList.size() == 0);
    }

    private PullToRefreshLayout.OnPullListener pullListener = new PullToRefreshLayout.OnPullListener()
    {
        @Override
        public void onRefresh(PullToRefreshLayout pullToRefreshLayout)
        {
            pageIndex = 1;
            initData();
        }

        @Override
        public void onLoadMore(PullToRefreshLayout pullToRefreshLayout)
        {
            pageIndex = companyList.size() / Utils.ONCECOUNT + 1;
            initData();
        }
    };

    private void initData() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getCompanyList("请稍等…");
            }
        }, 500);
    }

    /**
     * 获取公司列表
     *
     * @param alert
     */
    public void getCompanyList(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
            jsonObject.put("pageNum", 1);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/projectCompany/queryByConstructionId/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    CompanyListRes res = gson.fromJson(json, CompanyListRes.class);
                    if (res.getStatus() == 1) {
                        Message msg = handler.obtainMessage();
                        msg.what = Constants.UPDATE;
                        msg.obj = res.getValue();
                        msg.sendToTarget();
                    } else {
                        refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                        showToast(res.getMsg());
                    }
                } else {
                    refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                    showToast("系统异常");
                }
            }

            @Override
            public void onFailure(String json) {
                refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
            }
        });
    }

    @Override
    public void onClick(Object o) {
        Company company = (Company) o;
        if(company == null){
            return;
        }
        intent.putExtra("company", company);
        setResult(RESULT_OK, intent);
        finish();
    }

    @OnClick({R.id.back_tv})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back_tv:
                finish();
                break;
        }
    }
}
